﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.WebControls;

namespace SPHealth.SharePoint.dbSize.LAYOUTS.SPHealth.SharePoint.dbSize
{
    public partial class DatabaseSizeDetails : LayoutsPageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // find the content database passed via the query string
            foreach (SPWebApplication webApplication in SPWebService.ContentService.WebApplications)
            {
                if (webApplication.Status == SPObjectStatus.Online)
                {
                    // get a list of the content databases in the farm
                    foreach (SPContentDatabase contentDatabase in webApplication.ContentDatabases)
                    {
                        if (contentDatabase.Id.ToString().ToLower() == this.Request.QueryString["id"].ToLower())
                        {
                            // we've found our database
                            string logValues = GetDatabaseSizes(contentDatabase, false);
                            string dataValues = GetDatabaseSizes(contentDatabase, true);


                            // render our chart
                            StringBuilder sb = new StringBuilder();
                            sb.AppendLine("<div id='dbSizeChart' style='width: 700px; height: 400px;'/> ");
                            sb.AppendLine("<script type='text/javascript'> ");
                            sb.AppendLine("    $(document).ready(function () { ");
                            sb.AppendLine("        var logs = [" + logValues + "]; ");
                            sb.AppendLine("        var data = [" + dataValues + "]; ");
                            sb.AppendLine("        plot1 = $.jqplot('dbSizeChart', [logs, data], ");
                            sb.AppendLine("            { ");
                            sb.AppendLine("                animate: true, animateReplot: true, cursor: { show: true, zoom: true, looseZoom: true, showTooltip: false }, highlighter: { show: true, showLabel: true, tooltipAxes: 'y', sizeAdjust: 7.5, tooltipLocation: 'ne' }, legend: { show: true, location: 'nw' }, axesDefaults: { pad: 0 }, ");
                            sb.AppendLine("                series: [ ");
                            sb.AppendLine("                    { label: 'Logs', renderer: $.jqplot.BarRenderer, showHighlight: true, yaxis: 'y2axis', rendererOptions: { animation: { speed: 2500 }, barWidth: 15, barPadding: -15, barMargin: 0, highlightMouseOver: false} }, ");
                            sb.AppendLine("                    { label: 'Data', rendererOptions: { animation: { speed: 2000}}, showHighlight: true } ");
                            sb.AppendLine("                ], ");
                            sb.AppendLine("                axes: { ");
                            sb.AppendLine("                    xaxis: { renderer: $.jqplot.DateAxisRenderer, labelRenderer: $.jqplot.CanvasAxisLabelRenderer, tickRenderer: $.jqplot.CanvasAxisTickRenderer, tickOptions: { angle: 30 }, drawMajorGridlines: false, drawMinorGridlines: true, drawMajorTickMarks: true, rendererOptions: { tickInset: 0.5, minorTicks: 1} }, ");
                            sb.AppendLine("                    yaxis: { label: 'Data Size (MB)', labelRenderer: $.jqplot.CanvasAxisLabelRenderer, tickOptions: { formatString: \"%'d\" }, rendererOptions: { forceTickAt0: false }, drawMajorGridlines: false, drawMinorGridlines: false }, ");
                            sb.AppendLine("                    y2axis: { label: 'Log Size (MB)', labelRenderer: $.jqplot.CanvasAxisLabelRenderer, tickOptions: { formatString: \"%'d\" }, rendererOptions: { alignTicks: false, forceTickAt0: false }, drawMajorGridlines: false, drawMinorGridlines: false } ");
                            sb.AppendLine("                } ");
                            sb.AppendLine("            }); ");
                            sb.AppendLine("    }); ");
                            sb.AppendLine("</script> ");

                            c1.Text = sb.ToString();

                            break;
                        }
                    }
                }
            }

        }

        private static string GetDatabaseSizes(SPContentDatabase contentDatabase, bool showData)
        {
            string key = "SPHealth.DBSizeHistory";
            if (!showData)
                key = "SPHealth.LogSizeHistory";


            // the raw data will be a comma seperated string in date,size,date,size,date,size format
            StringBuilder values = new StringBuilder();
            if (contentDatabase.Properties.ContainsKey(key))
            {
                string rawData = contentDatabase.Properties[key].ToString();
                if (!string.IsNullOrEmpty(rawData))
                {
                    string[] parts = rawData.Split(new char[] { ',' });
                    if (parts.Length > 1)
                    {
                        // take every value pair
                        for (int x = 0; x <= parts.Length-1; x = x + 2)
                        {
                            values.Append(string.Format("['{0}', {1}]", parts[x], parts[x+1]));
                            if (x < parts.Length - 1)
                                values.Append(",");
                        }
                    }
                }
                else
                {
                    // no data found
                    values.Append(string.Format("['{0}', {1}]","2000-01-01",0));
                }
            }
            else
            {
                // no data found
                values.Append(string.Format("['{0}', {1}]", "2000-01-01", 0));
            }

            return values.ToString();
        }
    }
}
